﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MD5Encrypter.cs" company="DissingNelleman">
//   
// All rights reserved. </copyright>
// <summary>
//   The m d 5 encrypter.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace ServiceLibrary.Models
{
    using System;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;

    /// <summary>
    /// The m d 5 encrypter.
    /// </summary>
    public static class MD5Encrypter
    {
        #region Public Methods and Operators

        /// <summary>
        /// Encrypts the password using MD5 hashing with salt.
        /// </summary>
        /// <param name="salt">
        /// For password encryption, salt should be the Guid.ToString() of the User.ID
        /// </param>
        /// <param name="originalPassword">
        /// The unencrypted password.
        /// </param>
        /// <returns>
        /// The encrypted password.
        /// </returns>
        public static string EncryptPassword(string salt, string originalPassword)
        {
            if (originalPassword == null)
            {
                originalPassword = Guid.Empty.ToString();
            }

            // Declarations
            byte[] originalBytes;
            byte[] encodedBytes;
            byte[] saltBytes;
            MD5 md5;

            // Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
            md5 = new MD5CryptoServiceProvider();
            originalBytes = Encoding.Default.GetBytes(originalPassword);
            saltBytes = Encoding.Default.GetBytes(salt);
            encodedBytes = md5.ComputeHash(saltBytes.Concat(md5.ComputeHash(originalBytes)).ToArray());

            // Convert encoded bytes back to a 'readable' string
            return BitConverter.ToString(encodedBytes);
        }

        #endregion
    }
}